package com.inxedu.os.edu.controller.Template;

import com.inxedu.os.common.cache.CacheUtil;
import com.inxedu.os.common.controller.BaseController;
import com.inxedu.os.common.util.TemplateUtils;
import com.inxedu.os.edu.entity.templateoriginal.TemplateOriginal;
import com.inxedu.os.edu.service.templateoriginal.TemplateOriginalService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * @author www.inxedu.com
 *
 */
@Controller
	@RequestMapping("/admin/template")
public class AdminTemplateFileController extends BaseController{
	
	private static Logger logger = LoggerFactory.getLogger(AdminTemplateFileController.class);
	private static String userListPage = getViewPath("/admin/user/user-list");//学员列表页面
	@Autowired
	private TemplateOriginalService templateOriginalService;
	@InitBinder({"user"})
	public void initUser(WebDataBinder dinder){
		dinder.setFieldDefaultPrefix("user.");
	}

	/**
	 * 模板管理
	 */
	@RequestMapping("/file/list")
	public String templateFileList(HttpServletRequest request){
		try{

			request.setAttribute("fileList",TemplateUtils.queryTemplateFile(request.getSession().getServletContext().getRealPath("/")+"/template/templet1"));
			Map fileName = new HashMap();
			Map directoryName = new HashMap();
			Map message = new HashMap();
            Map change = new HashMap();
			message = getFileMap(request.getSession().getServletContext().getRealPath("/")+"/template/templet1");
			directoryName = (Map) message.get("directoryName");

			change = (Map) message.get("fileName");
            Iterator iterator = change.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry entry = (Map.Entry) iterator.next();
                String name = (String) entry.getKey();
                String value = entry.getValue().toString().replace("\\","/");
                fileName.put(name,value);
            }
			String moveFilePath;
			String moveFileName ="";
			if (CacheUtil.get("moveFilePath")!=null){
				moveFilePath = CacheUtil.get("moveFilePath").toString();
				moveFilePath = moveFilePath.replace("\\","/");
				request.setAttribute("moveFilePath",moveFilePath);
			}
			if (CacheUtil.get("moveFileName")!=null) {
				moveFileName = CacheUtil.get("moveFileName").toString();
				request.setAttribute("moveFileName",moveFileName);
			}
			request.setAttribute("hide","hide");
			String path = request.getSession().getServletContext().getRealPath("/")+"/template/templet1".replace("\\","/");
			request.setAttribute("directoryName",directoryName);
			request.setAttribute("fileName",fileName);
			request.setAttribute("path",path);
		}catch (Exception e) {
			logger.error("templateFileList()---error",e);
			return this.setExceptionRequest(request, e);

		}
		/*return getViewPath("/admin/template/template_list");*/
		return getViewPath("/admin/template/type_list");
	}
    /**
     * 模板列表
     */
    @RequestMapping("/file/htmlList")
    public String htmlList(HttpServletRequest request){
        try{
            Map fileName = new HashMap();
            Map directoryName = new HashMap();
            Map message = new HashMap();
            message = getFileMap(request.getSession().getServletContext().getRealPath("/")+"/template/templet1");
            directoryName = (Map) message.get("directoryName");
            fileName = (Map) message.get("fileName");
            Map htmlName = new HashMap();
            Iterator iterator = fileName.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry entry = (Map.Entry) iterator.next();
                String name = (String) entry.getKey();
                String value = entry.getValue().toString().replace("\\","/");
                if (name.substring(name.lastIndexOf(".")+1).equals("html")){
                    htmlName.put(name,value);
                }
            }
            request.setAttribute("directoryName",directoryName);
            request.setAttribute("fileName",fileName);
            request.setAttribute("htmlName",htmlName);
        }catch (Exception e) {
            logger.error("templateFileList()---error",e);
            return this.setExceptionRequest(request, e);

        }

        return getViewPath("/admin/template/html_list");
    }
	/**
	 * 读取txt文件的内容
	 * @param file 想要读取的文件对象
	 * @return 返回文件内容
	 */
	public static String txt2String(File file){
		StringBuilder result = new StringBuilder();
		try{
			BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
			String s = null;
			while((s = br.readLine())!=null){//使用readLine方法，一次读一行
				result.append(System.lineSeparator()+s);
			}
			br.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return result.toString();
	}
	/**
	 * 修改
	 */
	@RequestMapping("/file/toupdate")
	public String toupdateTemplateFile(HttpServletRequest request,String filePath){
		try{
			File file = new File(filePath);
			request.setAttribute("name",file.getName());
			request.setAttribute("path",file.getAbsolutePath());
			if (file.isDirectory()) {//文件夹
				request.setAttribute("path",file.getAbsolutePath());
			}else{//文件

			}
		}catch (Exception e) {
			logger.error("templateFileList()---error",e);
			return this.setExceptionRequest(request, e);

		}
		return getViewPath("/admin/template/template_list");
	}

	/**
	 * 读取某个文件夹下的所有文件
	 */
	public static boolean readfile(String filepath) throws IOException {
		try {
			File file = new File(filepath);
			if (!file.isDirectory()) {

			} else if (file.isDirectory()) {
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File readfile = new File(filepath + "/" + filelist[i]);
					if (!readfile.isDirectory()) {

					} else if (readfile.isDirectory()) {
						readfile(filepath + "/" + filelist[i]);
					}
				}

			}
		} catch (FileNotFoundException e) {
			//System.out.println("readfile()   Exception:" + e.getMessage());
		}
		return true;
	}

	/**
	 * 删除某个文件夹下的所有文件夹和文件
	 */
	public static boolean deletefile(String delpath)throws IOException {
			try {

				File file = new File(delpath);
				if (!file.isDirectory()) {
						file.delete();
				} else if (file.isDirectory()) {
						String[] filelist = file.list();
						for (int i = 0; i < filelist.length; i++) {
								File delfile = new File(delpath + "/" + filelist[i]);
								if (!delfile.isDirectory()) {
									delfile.delete();
									System.out.println("删除文件成功");
								} else if (delfile.isDirectory()) {
										deletefile(delpath + "/" + filelist[i]);
								}
						}
						file.delete();

				}

			} catch (FileNotFoundException e) {
					System.out.println("deletefile()   Exception:" + e.getMessage());
			}
		return true;
	}

	public static void main(String[] args) {
		try {
			readfile("E:\\软件\\53KFe:/videos");
			// deletefile("D:/file");
		} catch (FileNotFoundException ex) {
		} catch (IOException ex) {
		}
		System.out.println("ok");
	}

	/**
	 * 到子集菜单
	 */
	@RequestMapping("/file/toChildList")
	public String toChildList(HttpServletRequest request,String path){
		try {
			Map fileName = new HashMap();
			Map directoryName = new HashMap();
			Map message = new HashMap();
            Map change = new HashMap();
			message = getFileMap(path);
			directoryName = (Map) message.get("directoryName");
            change = (Map) message.get("fileName");
			String moveFilePath;
			String moveFileName ="";
			if (CacheUtil.get("moveFilePath")!=null){
				moveFilePath = CacheUtil.get("moveFilePath").toString();
				moveFilePath = moveFilePath.replace("\\","/");
				request.setAttribute("moveFilePath",moveFilePath);
			}
			if (CacheUtil.get("moveFileName")!=null) {
				moveFileName = CacheUtil.get("moveFileName").toString();
				request.setAttribute("moveFileName",moveFileName);
			}
            Iterator iterator = change.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry entry = (Map.Entry) iterator.next();
                String name = (String) entry.getKey();
                String value = entry.getValue().toString().replace("\\","/");
                fileName.put(name,value);
            }
			path = path.replace("\\","/");
			String ifPath = request.getSession().getServletContext().getRealPath("/")+"/template/templet1".replace("\\","/");
			ifPath = ifPath.substring(0,ifPath.length()-2);
			request.setAttribute("ifPath",ifPath);
			request.setAttribute("directoryName",directoryName);
			request.setAttribute("fileName",fileName);
			request.setAttribute("path",path);
		}catch (Exception e){
			logger.error("toChildList()---error",e);
			return this.setExceptionRequest(request, e);
		}
		return getViewPath("/admin/template/type_list");
	}
	//点击文件夹获得新的文件信息
	@RequestMapping("file/fileList")
	@ResponseBody
	public Map<String,Object> fileList(HttpServletRequest request) {
		Map<String,Object> json = new HashMap<String,Object>();
		try {
			Map fileName = new HashMap();
			Map directoryName = new HashMap();
			String path = request.getParameter("path");
			directoryName = getFileMap(path);
			Map message = new HashMap();
			message.put("directoryName",directoryName);
			message.put("fileName",fileName);
			json = this.setJson(true,"",message);
		}catch (Exception e){
			this.setAjaxException(json);
			logger.error("ifExist()--error",e);
		}
		return json;
	}
	//获取文件和文件夹
	public Map getFileMap(String filePath){
		Map directoryName = new HashMap();
		Map fileName = new HashMap();
		File file= new File(filePath);
		Map<String,Map> message = new HashMap();
		if (!file.isDirectory()){
			fileName.put(file.getName(),filePath+file.getName());
		}else if (file.isDirectory()){
			String[] fileList = file.list();
			for (int i=0;i<fileList.length;i++){
				File readFile = new File(filePath+fileList[i]);
				if (!readFile.isDirectory()){
					fileName.put(readFile.getName(),filePath+readFile.getName());
				}else if (readFile.isDirectory()){
					directoryName.put(readFile.getName(),filePath+readFile.getName());
				}
			}
		}
		message.put("fileName",fileName);
		message.put("directoryName",directoryName);

		return message;
	}
	//到修改文件页面
	@RequestMapping("/toUpdateFile")
	public String toChangeFile(HttpServletRequest request,String path){
		File file;
		try {
			file = new File(path);
			String newPath = file.getPath();
			newPath = newPath.replace("\\","/");
			String str = txt2String(file);
			String name = file.getName();
			/*格式化html文件*/
			Document document = Jsoup.parseBodyFragment(str);
			String html = document.body().html();
			html = html.replace("&lt;","<"+"");
			html = html.replace("&gt;",">"+"");
			TemplateOriginal templateOriginal = new TemplateOriginal();
			List<TemplateOriginal> templateOriginals = new ArrayList<>();
			templateOriginals = templateOriginalService.queryTemplateOriginalList(templateOriginal);
			for (int i=0;i<templateOriginals.size();i++){
				if (templateOriginals.get(i).getName().equals(name)){
					request.setAttribute("originalTemplet",true);
				}
			}
			request.setAttribute("str",html);
			request.setAttribute("name",name);
			request.setAttribute("path",newPath);
		}catch (Exception e){
			logger.error("toChangeFile()--error",e);
			return this.setExceptionRequest(request, e);
		}
		return getViewPath("/admin/template/change_file");
	}
	//到给文字着色页面
	@RequestMapping("/toChangeColor")
	public String toChangeColor(HttpServletRequest request,String path){
		File file;
		try {
			file = new File(path);
			String str = txt2String(file);
			request.setAttribute("str",str);
		}catch (Exception e){
			logger.error("toChangeColor()--error",e);
			return this.setExceptionRequest(request, e);
		}
		return getViewPath("/admin/template/change-color");
	}
	//修改名字
	@RequestMapping("/ajax/changeName")
	@ResponseBody
	public Map<String,Object> changeName(HttpServletRequest request) {
		Map<String,Object> json = new HashMap<String,Object>();
		String name = request.getParameter("name");
		String str = request.getParameter("str");
		String path = request.getParameter("path");
		String oldName = request.getParameter("oldName");
		File file;
		try {
			String newPath = path.substring(0,path.length()-oldName.length())+name;
			BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(newPath)));
			String[] strings = str.split("\\n");
			for (int i=0;i<strings.length;i++){
				bufferedWriter.write(strings[i]);
				bufferedWriter.newLine();
			}
			File oldFile = new File(path);
			oldFile.delete();
			bufferedWriter.flush();
			bufferedWriter.close();
			json = this.setJson(true,path.substring(0,path.length()-oldName.length()),null);
		}catch (Exception e){
			this.setAjaxException(json);
			logger.error("changeName()--error",e);
		}
		return json;
	}
	//判断文件是否已存在
	@RequestMapping("/ajax/ifExist")
	@ResponseBody
	public Map<String,Object> ifExist(HttpServletRequest request) {
		Map<String,Object> json = new HashMap<String,Object>();
		String filePath = "";
		try {
			String name = request.getParameter("name");
			String path = request.getParameter("path");
			String oldName = request.getParameter("oldName");
			String newPath = path.substring(0,path.length()-oldName.length())+name;
			Map fileName = new HashMap();
			fileName = (Map) getFileMap(path.substring(0,path.length()-oldName.length())).get("fileName");
			//fileName = getFileList(filePath);
			if (fileName.containsKey(name)){
				json = this.setJson(false,"是否替换原文件！",null);
				return json;
			}
			json = this.setJson(true,"",null);
		}catch (Exception e){
			this.setAjaxException(json);
			logger.error("ifExist()--error",e);
		}
		return json;
	}
	//保存更改文件
	@RequestMapping("/ajax/saveFile")
	@ResponseBody
	public Map<String,Object> saveFile(HttpServletRequest request){
		Map<String,Object> json = new HashMap<String,Object>();
		String path = request.getParameter("path");
		String name = request.getParameter("name");
		String str = request.getParameter("str");
		String oldName = request.getParameter("oldName");
		File file;
		try {
			String newPath = path.substring(0,path.length()-oldName.length())+name;
			file = new File(newPath);
			BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
			String[] strings = str.split("\\n");
			for (int i=0;i<strings.length;i++){
				bufferedWriter.write(strings[i]);
				bufferedWriter.newLine();
			}
			bufferedWriter.flush();
			bufferedWriter.close();
			json = this.setJson(true,path.substring(0,path.length()-oldName.length()),null);
		}catch (Exception e){
			this.setAjaxException(json);
			logger.error("saveFile()--error",e);
		}
		return json;
	}
	//删除文件
	@RequestMapping("/ajax/deleteFile")
	@ResponseBody
	public Map<String,Object> deleteFile(HttpServletRequest request){
		Map<String,Object> json = new HashMap<String,Object>();
		String path = request.getParameter("path");
		String name = request.getParameter("name");
		String oldName = request.getParameter("oldName");
		File file;
		Map fileName = new HashMap();
		try {
			String newPath = path.substring(0,path.length()-oldName.length())+name;
			fileName = (Map) getFileMap(path.substring(0,path.length()-oldName.length())).get("fileName");
			file = new File(newPath);
			if (file!=null||!file.equals("")){
				if (fileName.containsKey(name)){
					file.delete();
				}else if (!fileName.containsKey(name)){
					json = this.setJson(false,"文件不存在",null);
					return json;
				}
			}
			json = this.setJson(true,path.substring(0,path.length()-oldName.length()),null);
		}catch (Exception e){
			this.setAjaxException(json);
			logger.error("deleteFile()--error",e);
		}
		return json;
	}
	//复制文件
	@RequestMapping("/ajax/copyFile")
	@ResponseBody
	public Map<String,Object> copyFile(HttpServletRequest request){
		Map<String,Object> json = new HashMap<String,Object>();
		String filePath = "";
		String name = request.getParameter("name");
		String str = request.getParameter("str");
		String path = request.getParameter("path");
		String oldName = request.getParameter("oldName");
		try {
			File file;
		/*	int count = 0 ;
			if (CacheUtil.get(name)==null){
				CacheUtil.set(name,count);
			}
			count =	Integer.parseInt(CacheUtil.get(name).toString())+1;
			CacheUtil.set(name,count);*/
			if (name.substring(0,2).equals("副本")){
				if (name.substring(2,3).equals("-")){
					String newName = name.substring(0,2)+2+name.substring(2);
					file =  new File(path+name);
				}else {
					int i = Integer.parseInt(name.substring(2,3))+1;
					String newName = name.substring(0,2)+i+name.substring(3);
					file = new File(path.substring(0,path.length()-oldName.length())+newName);
				}
			}else {
				file =  new File(path.substring(0,path.length()-oldName.length())+"副本-"+name);

			}
			BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
			String[] strings = str.split("\\n");
			for (int i=0;i<strings.length;i++){
				bufferedWriter.write(strings[i]);
				bufferedWriter.newLine();
			}
			bufferedWriter.flush();
			bufferedWriter.close();
			json = this.setJson(true,path.substring(0,path.length()-oldName.length()),null);
		}catch (Exception e){
			this.setAjaxException(json);
			logger.error("copyFile()--error",e);
		}
		return json;
	}
	//移动文件
	@RequestMapping("/ajax/moveFile")
	@ResponseBody
	public Map<String,Object> moveFile(HttpServletRequest request) {
		Map<String,Object> json = new HashMap<String,Object>();
		String path = request.getParameter("path");
		String moveFileName = request.getParameter("oldName");
		try {
			String moveFilePath = path;
			CacheUtil.set("moveFileName",moveFileName);
			CacheUtil.set("moveFilePath",moveFilePath);
			json = this.setJson(true,"",null);
		}catch (Exception e){
			this.setAjaxException(json);
			logger.error("moveFile()--error",e);
		}
		return json;
	}
	//粘贴文件
	@RequestMapping("/ajax/changeFilePath")
	@ResponseBody
	public Map<String,Object>  changeFilePath(HttpServletRequest request) {
		Map<String,Object> json = new HashMap<String,Object>();
		String path = request.getParameter("path");
		String moveFileName = request.getParameter("moveFileName");
		String moveFilePath = request.getParameter("moveFilePath");
		String filePath = "";
		try {
			File file = new File(moveFilePath);
			File newFile = new File(path+moveFileName);
			file.renameTo(newFile);
			CacheUtil.remove("moveFileName");
			CacheUtil.remove("moveFilePath");
			json = this.setJson(true,path,null);
		}catch (Exception e){
			this.setAjaxException(json);
			logger.error("changeFilePath()--error",e);
		}
		return json;
	}


	/**
	 * 选择模板列表
	 */
	@RequestMapping("/file/selecthtmlList")
	public String selctHtmlList(HttpServletRequest request){
		try{
			Map fileName = new HashMap();
			Map directoryName = new HashMap();
			Map message = new HashMap();
			message = getFileMap(request.getSession().getServletContext().getRealPath("/")+"/template/templet1");
			directoryName = (Map) message.get("directoryName");
			fileName = (Map) message.get("fileName");
			Map htmlName = new HashMap();
			Iterator iterator = fileName.entrySet().iterator();
			while (iterator.hasNext()){
				Map.Entry entry = (Map.Entry) iterator.next();
				String name = (String) entry.getKey();
				String value = entry.getValue().toString();
				value=value.replace(request.getSession().getServletContext().getRealPath("/"), "/");
				if (name.substring(name.lastIndexOf(".")+1).equals("html")){
					htmlName.put(name,value);
				}
			}
			request.setAttribute("directoryName",directoryName);
			request.setAttribute("fileName",fileName);
			request.setAttribute("htmlName",htmlName);
		}catch (Exception e) {
			logger.error("selctHtmlList()---error",e);
			return this.setExceptionRequest(request, e);

		}

		return getViewPath("/admin/template/html_list_select");
	}
	//删除文件夹
	@RequestMapping("/ajax/deleteDirectory")
	@ResponseBody
	public Map<String,Object> deleteDirectory(HttpServletRequest request){
		Map<String,Object> json = new HashMap<String,Object>();
		String path = request.getParameter("path");
		File file;
		try {
			file = new File(path);
			if (file.isDirectory()){
				deletefile(path);
				file.delete();
			}else {
				json = this.setJson(false,"没有找到文件夹",null);
				return json;
			}
			json = this.setJson(true,"",null);
		}catch (Exception e){
			this.setAjaxException(json);
			logger.error("deleteDirectory()--error",e);
		}
		return json;
	}
	/*还原所有模板*/
	@RequestMapping("/ajax/recovery")
	@ResponseBody
	public Map<String,Object> recovery(HttpServletRequest request){
		Map<String,Object> json = new HashMap<String,Object>();
		try {
			TemplateOriginal templateOriginal = new TemplateOriginal();
			List<TemplateOriginal> templateOriginals = new ArrayList<>();
			templateOriginals = templateOriginalService.queryTemplateOriginalList(templateOriginal);
			for (int i=0;i<templateOriginals.size();i++){
				File file = new File(request.getSession().getServletContext().getRealPath("/")+"/template/templet1/"+templateOriginals.get(i).getName());
				PrintWriter printWriter= new PrintWriter(new FileWriter(file));
				printWriter.write(templateOriginals.get(i).getContent());
				printWriter.flush();
				printWriter.close();
			}
			json = this.setJson(true,"",null);
		}catch (Exception e){
			this.setAjaxException(json);
			logger.error("recovery()--error",e);
		}
		return json;
	}

	/*还原某个模板*/
	@RequestMapping("/ajax/recoveryThis")
	@ResponseBody
	public Map<String,Object> recoveryThis(HttpServletRequest request){
		Map<String,Object> json = new HashMap<String,Object>();
		try {
			String filePath = request.getParameter("filePath");
			String fileName = filePath.substring(filePath.lastIndexOf("\\")+1);
			TemplateOriginal templateOriginal = new TemplateOriginal();
			List<TemplateOriginal> templateOriginals = new ArrayList<>();
			templateOriginals = templateOriginalService.queryTemplateOriginalList(templateOriginal);
			for (int i=0;i<templateOriginals.size();i++){
				if (fileName.equals(templateOriginals.get(i).getName())){
					/*File file = new File(filePath);
					PrintWriter printWriter = new PrintWriter(new FileWriter(file));
					printWriter.write(templateOriginals.get(i).getContent());*/
					json = this.setJson(true,"模板已还原，保存后生效！",templateOriginals.get(i).getContent());
					return json;
				}
			}
			json = this.setJson(false,"项目初始模板不包含该模板！",null);
		}catch (Exception e){
			this.setAjaxException(json);
			logger.error("recovery()--error",e);
		}
		return json;
	}
}